package com.ww.springboot.boot.javabase.stream;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2025-08-07 10:29
 */
public class StreamReduceDemo {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // 在并行流中求和
        int sum = numbers.parallelStream()
                .reduce(0,
                        Integer::sum,           // accumulator
                        Integer::sum);          // combiner

        System.out.println(sum);

        sum = numbers.stream()
                .reduce(0,
                        Integer::sum);          // combiner

        System.out.println(sum);

        sum = numbers.stream()
                .reduce(Integer::sum).get();          // combiner
        System.out.println(sum);
        sum = numbers.stream().mapToInt(i -> i).sum();
        System.out.println(sum);
        sum = numbers.stream().collect(Collectors.summingInt(i -> i + 1));
        System.out.println(sum);

        List<String> words = Arrays.asList("Hello", "World", "Java");

        // 带分隔符连接
        String result = words.stream().reduce("", (a, b) -> a + "," + b);

        System.out.println(result);

        List<Integer> numbers2 = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);

        Optional<Integer> max = numbers2.stream().reduce(Integer::max);
        Optional<Integer> min = numbers2.stream().reduce(Integer::min);
        System.out.println(max.get());
        System.out.println(min.get());
    }
}
